import datetime
from datetime import timedelta

from rest_framework import serializers
from user.models import User, Clazz, UserTask


class UserSerializers(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'password', 'first_name', 'last_name', 'is_active', 'is_staff', 'clazz']

    extra_kwargs = {
        'password': {'write_only': True}
    }

    def create(self, validated_data):
        # 在创建账户的时候,让账号自动激活
        validated_data['is_active'] = True
        return User.objects.create_user(**validated_data)

    def update(self, instance, validated_data):
        # 注意：这里通常不需要自定义update方法，除非您有特殊的逻辑要处理
        # 因为DRF会自动处理外键关系的更新
        instance.clazz = validated_data.get('clazz_id', instance.clazz_id)
        print(instance.clazz)
        instance.save()
        return instance



### 定义一个新的序列化器
class UserTaskStatisticsSerializer(serializers.ModelSerializer):
    total_tasks = serializers.SerializerMethodField()
    not_started_tasks = serializers.SerializerMethodField()
    not_checked_tasks = serializers.SerializerMethodField()
    cant_do_tasks = serializers.SerializerMethodField()
    task_completion_rate = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ['id','first_name','last_name','username', 'total_tasks', 'not_started_tasks', 'not_checked_tasks', 'cant_do_tasks',
                  'task_completion_rate']

    def get_total_tasks(self, obj):
        return UserTask.objects.filter(user=obj).count()

    def get_not_started_tasks(self, obj):
        return UserTask.objects.filter(user=obj, task_state=0).count()

    def get_not_checked_tasks(self, obj):
        return UserTask.objects.filter(user=obj, task_state__in=[1, 2, 3]).count()  # 假设进行中、不会做、已提交都算作未检查

    def get_cant_do_tasks(self, obj):
        return UserTask.objects.filter(user=obj, task_state=2).count()

    def get_task_completion_rate(self, obj):
        total_tasks = UserTask.objects.filter(user=obj).count()
        if total_tasks == 0:
            return 0  # 避免除以零错误
        completed_tasks = UserTask.objects.filter(user=obj, task_state=6).count()
        return (completed_tasks / total_tasks) * 100


